// ProcessBrowse.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <iostream>
#include <stdio.h>
#include <string>
#include "windows.h"
#include "tlhelp32.h"
#include "Psapi.h"
#pragma comment(lib,"psapi.lib")


void getProcessModules(DWORD processID){
	_tprintf(TEXT("---------------------------------------\n"));
	_tprintf(TEXT("-- Process id = %d\n"), processID);

	MODULEENTRY32 moduleEntry;
    moduleEntry.dwSize = sizeof(MODULEENTRY32);

    HANDLE moduleSnapHandle = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, processID);
        
    if (!Module32First(moduleSnapHandle, &moduleEntry)){
		_tprintf(TEXT("Error: can`t get information about the first module associated with a process %d.\n"), processID);
        CloseHandle(moduleSnapHandle);
        return;
    }
     
	_tprintf(TEXT("-- Process path: %s\n"), moduleEntry.szExePath);
	_tprintf(TEXT("-- Process modules:\n"));
    do{
		_tprintf(TEXT("--      %s\n"), moduleEntry.szModule);
    } while (Module32Next(moduleSnapHandle, &moduleEntry));
}

void getProcessMemoryParam(DWORD processID)
{
	HANDLE processHandle = OpenProcess(PROCESS_ALL_ACCESS, false, processID);
    PROCESS_MEMORY_COUNTERS memCounter;
    if(GetProcessMemoryInfo(processHandle, &memCounter, sizeof(memCounter))){
		_tprintf(TEXT("-- Process memory:\n"));
		_tprintf(TEXT("--      Working set size  Peak      Current\n"));
		_tprintf(TEXT("--                        %d   %d\n\n"), memCounter.PeakWorkingSetSize, memCounter.WorkingSetSize);
		_tprintf(TEXT("--      Pagefile usage    Peak      Current\n"));
		_tprintf(TEXT("--                        %d   %d\n"), memCounter.PeakPagefileUsage, memCounter.PagefileUsage);
	}
	CloseHandle(processHandle);
}


int _tmain(int argc, _TCHAR* argv[])
{
	PROCESSENTRY32 processEntry;
    processEntry.dwSize = sizeof(PROCESSENTRY32);

    HANDLE snapshotHandle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (!Process32First(snapshotHandle, &processEntry))
    {
		std::cout<<"Error: can`t get information about the first process encountered in a system snapshot."<<std::endl;
        CloseHandle(snapshotHandle);
        return 1;
    }
    do
    {
		getProcessModules(processEntry.th32ProcessID);
		getProcessMemoryParam(processEntry.th32ProcessID);
    } while (Process32Next(snapshotHandle, &processEntry));
    
    CloseHandle(snapshotHandle);

	getchar();

	return 0;
}

